import Vue from 'vue'
import Router from 'vue-router'

import login from '../views/login.vue'
import home from '../views/Home.vue'
import welcome from '../views/welcome/Welcome.vue'
import user from '../views/user/User.vue'
import rights from '../views/right/Rights.vue'
import roles from '../views/right/Roles.vue'
import category from '../views/category/Category.vue'
import goods from '../views/goods/Goods.vue'
import addGoods from '../views/goods/AddGoods.vue'

Vue.use(Router)

let router = new Router({
  routes: [{
      path: '/login',
      name: 'Login',
      component: login
    },
    {
      path: '/',
      name: 'Home',
      component: home,
      redirect: {
        path: 'welcome'
      },
      children: [{
          name: 'Welcome',
          path: 'welcome',
          component: welcome
        }, {
          name: 'Users',
          path: 'users',
          component: user
        }, {
          name: 'Rights',
          path: 'rights',
          component: rights
        }, {
          name: 'Roles',
          path: 'roles',
          component: roles
        }, {
          name: 'Category',
          path: 'categories',
          component: category
        },
        {
          name: 'Goods',
          path: 'goods',
          component: goods
        }, {
          name: 'AddGoods',
          path: 'toadd',
          component: addGoods
        }
      ]
    }
  ]
})

// 注册一个全局守卫，作用是在路由跳转前，对路由进行判断，防止未登录的用户跳转到其他需要登录的页面去
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('mytoken')
  // 如果已经登录，放行
  if (token) {
    next()
  } else {
    // 如果没有登录，访问非登录页面,则跳转到登录页面
    if (to.path !== '/login') {
      next({
        path: '/login'
      })
    } else {
      // 如果没有登录，但访问的是登录页面,直接进入
      next()
    }
  }
})

export default router
